const fs = require('fs')
const file = 'report.md'
const lessons = [
    'lesson-2-1-11',
    'lesson-2-1-12',
    'lesson-2-1-13',
    'lesson-2-1-14'
]
const learning = require('./learning.json')

let content = lessons.map(lessonContent).join('\n')
content += summary()

fs.writeFile(`./${file}`, content, function (err) {
    if (err) {
        return console.log(err)
    }
    console.log(`${file} is write.`)
})

function lessonContent(lesson) {
    const data = require(`./${lesson}.json`)
    const usedWords = new Set()
    const chars = data.write.characters.map(char => {
        const words = data.write.words.filter(w => {
            if (w.indexOf(char) !== -1) {
                usedWords.add(w)
                return true
            }

            return false
        })
        return {
            char,
            words
        }
    })
    const highlightWords = data.write.words.filter(w => !usedWords.has(w))


    function outputWords(chars) {
        let wordContent = ''

        chars.forEach(char => {
            let wordsStr = char.words.map(w => `(${highlightWrong(w)})`).join(' ')
            wordContent += `${char.char}  ${wordsStr}  \n`
        })

        return wordContent;
    }

    function outputHighlightWords(words) {
        return words.join(' ')
    }

    function highlightWrong(word) {

        let wrong = learning[word] && learning[word].length > 0 ? learning[word][learning[word].length - 1].wrong : [];

        if (wrong.length > 0) {
            wrong.forEach(c => {
                word = word.replace(c, `<font color='red'>${c}</font>`)
            })
        }

        return word
    }

    let content = `## ${data.title} \n` +
        '### 生字词 \n' +
        `${outputWords(chars)} \n` +
        '### 重点词 \n' +
        `${outputHighlightWords(highlightWords)} \n`

    return content
}

function summary() {
    let wordsNumber = 0

    lessons.forEach(lesson => {
        let data = require(`./${lesson}.json`)
        wordsNumber += data.write.words.length

    })

    let content = `## 统计\n` +
        `正在学习：${wordsNumber}个词语`;
    return content;
}
